package com.ztrue.common.serializing.impl;

import com.ztrue.common.serializing.IByteSerializer;
import com.ztrue.common.serializing.SerializeException;

import java.io.*;

/**
 * @author zhangw
 * @date 2016/11/2 11:40
 * @version: 1.0
 */
public class ObjectStreamSerializer implements IByteSerializer {
    /**
     * 序列化
     *
     * @param obj
     * @return
     */
    public byte[] serialize(Object obj) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            if (obj != null) {
                baos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(baos);
                oos.writeObject(obj);
                return baos.toByteArray();
            } else {
                return null;
            }
        } catch (IOException e) {
            throw new SerializeException(e.getMessage(), e);
        }
    }

    /**
     * 反序列化
     *
     * @param bytes
     * @return
     */
    public Object deserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            if (bytes != null) {
                bais = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bais);
                return ois.readObject();
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new SerializeException(e.getMessage(), e);
        }
    }
}
